package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.QywxUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.Message;
import com.ruoyi.system.mapper.MessageMapper;
import com.ruoyi.system.service.IMessageService;
import com.ruoyi.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements IMessageService {

    private final MessageMapper messageMapper;

    private final ISysUserService sysUserService;

    public void sendProjectMsgByRoleIds(Integer projectId,String roleIds,String content){
        List<SysUser> messageList = sysUserService.getMessageList(projectId, roleIds);
        List<Long> userIdList = messageList.stream().map(SysUser::getUserId).collect(Collectors.toList());
        userIdList.forEach(m->{
            Message message = new Message();
            message.setIsRead(0);
            message.setContent(content);
            message.setCreatedTime(new Date());
            message.setUserId(m);
            save(message);
        });
        List<String> codeList = new ArrayList<>();
        messageList.forEach(m->{
            if (StringUtils.isNotEmpty(m.getCode())){
                codeList.add(m.getCode());
            }
        });
        if (codeList.size() > 0){
            QywxUtil.sendMsg(QywxUtil.getToken(),codeList, content);
        }
    }

    @Override
    public void sendProjectMsgByUserIds(String userIds, String content) {
        List<String> userIdList = Arrays.asList(userIds.split(","));
        SysUser user = new SysUser();
        user.setUserIdList(userIdList.stream().map(m->Integer.parseInt(m)).collect(Collectors.toList()));
        List<SysUser> userList = sysUserService.selectList(user);
        userIdList.forEach(m->{
            Message message = new Message();
            message.setIsRead(0);
            message.setContent(content);
            message.setCreatedTime(new Date());
            message.setUserId(Long.parseLong(m));
            save(message);
        });
        List<String> codeList = new ArrayList<>();
        userList.forEach(m->{
            if (StringUtils.isNotEmpty(m.getCode())){
                codeList.add(m.getCode());
            }
        });
        if (codeList.size() > 0){
            QywxUtil.sendMsg(QywxUtil.getToken(),codeList, content);
        }
    }
}
